package com.mulanweb.api.module.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.PascalNameFilter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;

/**
 * Created by Administrator on 2016/8/19.
 */
public class BaseController extends Controller{

    protected int getPageNumber()
    {
        return super.getParaToInt("PageNumber");
    }

    protected int getPageSize()
    {
        return super.getParaToInt("PageSize");
    }

    protected void returnJson(int code, String message)
    {
        Ret ret = Ret.create("ReturnCode", code);
        if (StrKit.notBlank(message))
        {
            ret.put("AlertMessage", message);
        }
        super.renderJson(ret.getData());
    }

    protected void returnFailureJson()
    {
        this.returnJson(0, "操作失败");
    }

    protected void returnSuccessJson()
    {
        this.returnJson(1, "操作成功");
    }

    protected void returnSuccessJson(Object object)
    {
        Ret ret = Ret.create("ReturnCode", 1);
        if (null != object)
        {
            ret.put("DataList", object);
        } else
        {
            ret.put("DataList", new Object());
        }
        super.renderJson(JSON.toJSONString(ret.getData(), new PascalNameFilter(), SerializerFeature.DisableCircularReferenceDetect));
    }

    protected Ret pageToRet(Page<?> page)
    {
        Ret ret = Ret.create("ReturnCode", 1);
        ret.put("TotalRow", page.getTotalRow());
        ret.put("TotalPage", page.getTotalPage());
        ret.put("PageNumber", page.getPageNumber());
        ret.put("PageSize", page.getPageSize());
        ret.put("DataList", page.getList());
        return ret;
    }

    protected void returnPageModelJson(Page<? extends Model> page)
    {
        page.getList().forEach(row -> {
            row.remove("tempcolumn");
            row.remove("temprownumber");
        });
        super.renderJson(JSON.toJSONString(pageToRet(page).getData(), new PascalNameFilter(), SerializerFeature.DisableCircularReferenceDetect));
    }
}
